#### INSTALL AND LOAD PACKAGES ==========================================================

# install pacman package if not installed -----------------------------------------------
suppressWarnings(if (!require("pacman")) install.packages("pacman"))

# load packages and install if not installed --------------------------------------------
pacman::p_load(haven, magrittr, dplyr, readr, ggplot2, forcats, lubridate, tidyr,
               psych, estimatr, MatchIt, modelsummary, broom, gt, gtExtras, scales,
               webshot2, patchwork, kableExtra, xtable,
               install = TRUE,
               update = FALSE)

# show loaded packages ------------------------------------------------------------------
cat("loaded packages\n")
print(pacman::p_loaded())

lm_robust_concessions <- function(x, data, type, depvar){
  a <- estimatr::lm_robust(x, data = data) 
  b <- broom::tidy(a, conf.int = T) %>%
    dplyr::mutate(type = type,
                  model = dplyr::case_when(outcome == "scaled_colconce4" ~ "(Political)\nParticipate in\npolitics",
                                           outcome == "scaled_colpact11" ~ "(Political)\nSecurity and\nmedia guarantees",
                                           outcome == "scaled_colpact11" ~ "(Political)\nSecurity and\nmedia guarantees",
                                           outcome == "scaled_colpact11a" ~ "(Judicial)\nDeprivation of\nliberty",
                                           outcome == "scaled_colpact1" ~ "(Judicial)\nNo jail for rank\nmembers",
                                           outcome == "scaled_colpact14" ~ "(Territorial)\nConcentration in\nsome regions",
                                           outcome == "scaled_colpact8" ~ "Seats for conflict regions",
                                           outcome == "scaled_colpact9" ~ "Peasant Reserve Zones",
                                           outcome == "scaled_colpact10" ~ "Vacant land",
                                           outcome == "scaled_colpact12" ~ "Coca crops",
                                           outcome == "scaled_colpact13" ~ "Military and police justice",),
                  model_color = factor(dplyr::case_when(outcome == "scaled_colconce4" ~ "<span style='color:#d95f0e'>(Political)</span><br>Participate in<br>politics",
                                                        outcome == "scaled_colpact11" ~ "<span style='color:#d95f0e'>(Political)</span><br>Security and<br>media guarantees",
                                                        outcome == "scaled_colpact11a" ~"<span style='color:#9ebcda'>(Judicial)</span><br>Deprivation of<br>liberty",
                                                        outcome == "scaled_colpact1" ~  "<span style='color:#9ebcda'>(Judicial)</span><br>No jail for rank<br>members",
                                                        outcome == "scaled_colpact14" ~ "<span style='color:#8856a7'>(Territorial)</span><br>Concentration in<br>some regions"),
                                       levels = c("<span style='color:#d95f0e'>(Political)</span><br>Participate in<br>politics",
                                                  "<span style='color:#d95f0e'>(Political)</span><br>Security and<br>media guarantees",
                                                  "<span style='color:#9ebcda'>(Judicial)</span><br>Deprivation of<br>liberty",
                                                  "<span style='color:#9ebcda'>(Judicial)</span><br>No jail for rank<br>members",
                                                  "<span style='color:#8856a7'>(Territorial)</span><br>Concentration in<br>some regions"))) %>%
    dplyr::filter(term == "d") %>% 
    dplyr::select(outcome, dplyr::everything()) 
  
  return(b)
  
}

model_concessions <- function(depvar, covars, data, type) {
  formulas_list <- list()
  for (i in depvar) {
    formulas_list[[i]] <- as.formula(paste0(i, " ~ ", paste0(covars, collapse = "+")))
  }
  
  model_list <- lapply(formulas_list, lm_robust_concessions, data = data, type = type, depvar = depvar)
  
  return(model_list)
}


lm_robust_table <- function(x, data, type, depvar){
  a <- estimatr::lm_robust(x, data = data) 
  b <- broom::tidy(a, conf.int = T) %>%
    dplyr::mutate(type = type,
                  model = dplyr::case_when(outcome == "scaled_colconce4" ~ "(Political)\nParticipate in\npolitics",
                                           outcome == "scaled_colpact11" ~ "(Political)\nSecurity and\nmedia guarantees",
                                           outcome == "scaled_colpact11" ~ "(Political)\nSecurity and\nmedia guarantees",
                                           outcome == "scaled_colpact11a" ~ "(Judicial)\nDeprivation of\nliberty",
                                           outcome == "scaled_colpact1" ~ "(Judicial)\nNo jail for rank\nmembers",
                                           outcome == "scaled_colpact14" ~ "(Territorial)\nConcentration in\nsome regions"),
                  model_color = factor(dplyr::case_when(outcome == "scaled_colconce4" ~ "<span style='color:#d95f0e'>(Political)</span><br>Participate in<br>politics",
                                                        outcome == "scaled_colpact11" ~ "<span style='color:#d95f0e'>(Political)</span><br>Security and<br>media guarantees",
                                                        outcome == "scaled_colpact11a" ~"<span style='color:#9ebcda'>(Judicial)</span><br>Deprivation of<br>liberty",
                                                        outcome == "scaled_colpact1" ~  "<span style='color:#9ebcda'>(Judicial)</span><br>No jail for rank<br>members",
                                                        outcome == "scaled_colpact14" ~ "<span style='color:#8856a7'>(Territorial)</span><br>Concentration in<br>some regions"),
                                       levels = c("<span style='color:#d95f0e'>(Political)</span><br>Participate in<br>politics",
                                                  "<span style='color:#d95f0e'>(Political)</span><br>Security and<br>media guarantees",
                                                  "<span style='color:#9ebcda'>(Judicial)</span><br>Deprivation of<br>liberty",
                                                  "<span style='color:#9ebcda'>(Judicial)</span><br>No jail for rank<br>members",
                                                  "<span style='color:#8856a7'>(Territorial)</span><br>Concentration in<br>some regions"))) %>%
    dplyr::filter(term == "d") %>% 
    dplyr::select(outcome, dplyr::everything()) 
  
  return(b)
  
}

model_bandwiths <- function(depvar, covars, data, type) {
  formulas_list <- list()
  for (i in depvar) {
    formulas_list[[i]] <- as.formula(paste0(i, " ~ ", paste0(covars, collapse = "+")))
  }
  
  #model_list <- lapply(formulas_list, lm_robust_table, data = data, type = type, depvar = depvar)
  
  return(formulas_list)
}


covariate_map <- c("d"="Exposure to Peace Plebiscite (D)",
                   "p15"="Placebo (-15 days)",
                   "p30"="Placebo (-30 days)",
                   "p45"="Placebo (-45 days)",
                   "age"="Age",
                   "female"="Female",
                   "edu"="Years of education", 
                   "urban"="Urban",
                   "estrato"="Income group",
                   "votesantos"="Vote Incumbent (Santos)",
                   "victim_ruv"="Victim (Unified Victim Registry)",
                   "relative_farc_vict"="Family victimized by FARC",
                   "conflict_zone"="Conflict-zone")

covariate_map_lapop13 <- c("d"="October 2, 2013 (D)",
                           "p15"="Placebo (-15 days)",
                           "p30"="Placebo (-30 days)",
                           "p45"="Placebo (-45 days)",
                           "age"="Age",
                           "female"="Female",
                           "edu"="Years of education", 
                           "urban"="Urban",
                           "estrato"="Income group",
                           "votesantos"="Vote Incumbent (Santos)",
                           "victim_ruv"="Victim (Unified Victim Registry)",
                           "relative_farc_vict"="Family victimized by FARC",
                           "conflict_zone"="Conflict-zone")

run_loo_regression <- function(formula, region_vector, data) {
  
  model_results <- list()
  
  # Iterate over each region
  for (exclude_region in region_vector) {
    # Create a subset of the data excluding the current region
    subset_data <- dplyr::filter(data, prov_label != exclude_region)
    
    # Run the model on the subsetted data
    model <- estimatr::lm_robust(formula, data = subset_data)
    
    # Store the model results
    model_results[[exclude_region]] <- broom::tidy(model)
  }
  
  result_df <- dplyr::bind_rows(model_results, .id = "id") %>%
    dplyr::filter(term == "d")
  
  return(result_df)
}

firstup <- function(x) {
  substr(x, 1, 1) <- toupper(substr(x, 1, 1))
  x
}

table.rma <- function(x, ...) {
  with(
    x,
    data.frame(
      estimate = b,
      std.error = se,
      z.value = zval,
      conf.low = ci.lb,
      conf.high = ci.ub,
      p.value = pval))
}

latex_reg <- function(x, ...) {
  with(
    x,
    data.frame(
      estimate = paste0("$",estimate,"$"),
      k = paste0("$",k,"$"),
      std.error = paste0("$",std.error,"$"),
      z.value = paste0("$",z.value,"$"),
      conf.low = paste0("$",conf.low,"$"),
      conf.high = paste0("$",conf.high,"$"),
      p.value = paste0("$",p.value,"$"
      )
    ))
}
